use crate::extends::db::RB;
use crate::extends::jwt;
use chrono::prelude::*;
use jsonwebtoken::{
    decode, encode, Algorithm, DecodingKey, EncodingKey, Header, TokenData, Validation,
};
use serde_json::Value;
use crate::extends::config::CONFIG;
use std::time::{SystemTime, UNIX_EPOCH};
//登录成功则返回token
pub async fn login(userName: String, passwordMd5: String) -> String {
    //begin
    let mut tx = RB.acquire_begin().await.unwrap();

    let mut token = String::from("");
    let (v, count) = tx
        .fetch::<serde_json::Value>(&format!(
            "select id from sys_user where login_user_name='{}' and  login_password='{}'",
            userName, passwordMd5
        ))
        .await
        .unwrap();
    //commit or rollback
    tx.commit().await.unwrap();

    if count > 0 {
        let v0 = &v[0];

        println!("v0={:?}",v0);
        //用户ID
        let user_id = v0["id"].as_str().unwrap();


        let start = SystemTime::now();
        let start_secs =start.duration_since(UNIX_EPOCH).expect("Time went backwards").as_secs();

        let my_claims = jwt::Claims {
            sub: user_id.to_owned(),
            //超时时间：当前时间+1000*60*60秒
            exp: ((start_secs + 60 * 60) as usize),
        };
        //secret +盐  123
        token = encode(
            &Header::default(),
            &my_claims,
            &EncodingKey::from_secret(CONFIG.jwt.secret.as_ref()),
        )
        .unwrap();
    }

    return token;
}
